package com.newgrand.service.impl;

import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.newgrand.domain.dbo.Pcm3CntM;
import com.newgrand.domain.dbo.Pcm3CntPayM;
import com.newgrand.domain.dbo.ProjectTable;
import com.newgrand.domain.model.*;
import com.newgrand.mapper.Pcm3CntMMapper;
import com.newgrand.mapper.Pcm3CntPayMMapper;
import com.newgrand.mapper.ProjectTableMapper;
import com.newgrand.service.AttachmentService;
import com.newgrand.service.MonthlyValuationsService;
import com.newgrand.utils.*;
import com.newgrand.utils.i8util.I8Converter;
import com.newgrand.utils.i8util.I8Request;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.stream.Collectors;

/**
 * m
 *
 * @创建人：ZhaoFengjie
 * @修改人：ZhaoFengjie
 * @创建时间：17:29 2022/10/17
 * @修改时间:：17:29 2022/10/17
 */
@Service
public class MonthlyValuationsImpl extends GetPhIdHelper implements MonthlyValuationsService {

    private static final OpenApiClient client = new OpenApiClient(YamlConstants.getPropertiesKey("mc.baseUrl"), YamlConstants.getPropertiesKey("mc.accessId"), YamlConstants.getPropertiesKey("mc.secretKey"));
    private static final String mainApi = "/sc/api/project-monthly-valuations?projectId=%s&subcontractId=%s";
    private static final String detailApi = "/sc/api/project-monthly-valuation/items?projectId=%s&subcontractId=%s&valuationId=%s";
    private static final String attachApi = "/sc/api/monthly-valuation-attachments?projectId=%s&valuationId=%s";
    private static Logger logger = LogManager.getLogger("logger");
    private static NGLog ngLog = new NGLog();
    @Resource
    private I8Request i8Request;
    private static String mstformData = "{\"form\":{\"key\":\"PhId\",\"newRow\":{\"BillNo\":\"cece\",\"Title\":\"ces\",\"BillDt\":\"2022-11-12\",\"PhidCnt\":\"758221111002017\",\"CntTitle\":\"二工区桥梁（基础及下构）工程劳务分包合同\",\"user_jjqs\":\"\",\"Cycle\":\"0\",\"DtStart\":\"\",\"PhidPc\":\"758220928000001\",\"PhidOCode\":\"758220810001001\",\"DtEnd\":\"\",\"RecCompName\":\"\",\"PhidTrOcode\":\"\",\"AppAmtVatFc\":29108.21,\"user_bqbhsje\":\"\",\"user_bqse\":\"\",\"user_ljjsse\":\"\",\"DescAmtVat\":0,\"RewardsAmtVat\":0,\"AmtSumAll\":29108.21,\"SumPayAmt\":\"\",\"user_ljjsbshje\":\"\",\"SumAmtDivcnt\":\"\",\"SumPayAmtAll\":\"\",\"SumAmtAllDivcnt\":\"\",\"SumBalAmt\":\"\",\"SumBalBl\":\"\",\"BalAmtAll\":\"\",\"CountAgeDt\":\"\",\"Remarks\":\"\",\"PhidCntType\":\"758220811000002\",\"PrintCount\":\"\",\"AmtSumAllBb\":29108.21,\"SumBl\":\"\",\"ThisPayAmt\":0,\"SumYsAmt\":\"\",\"RecOrg\":\"758220829000737\",\"PhidCountAge\":\"0\",\"PhidApp\":\"\",\"CurrType\":\"1\",\"ExchRate\":1,\"AppAmtVat\":29108.21,\"AppAmt\":29108.21,\"AppAmtFc\":29108.21,\"AuxName1\":\"\",\"AuxName2\":\"\",\"AuxName3\":\"\",\"PhidDept\":\"0\",\"PhidYsfl\":\"12\",\"BRPcNo\":\"10177\",\"BRCntNo\":\"JZ-JGJJLL07B2021-1019\",\"Creator\":\"758220811000001\",\"NgInsertDt\":\"2022-11-12 14:34:49\",\"SumWagesAmt\":\"\",\"ListFilterVal\":\"\",\"QueryField1Val\":\"\",\"QueryField2Val\":\"\",\"UIMultiConfigID\":\"\",\"AuxItems1\":\"\",\"AuxItems2\":\"\",\"AuxItems3\":\"\",\"PhId\":\"\",\"PhidSchemeId\":\"758221028000001\",\"ImpInfo\":\"\",\"NgRecordVer\":\"\",\"PhidSourcemid\":\"\",\"ItemResource\":\"\",\"WfFlg\":\"\",\"DaFlg\":\"\",\"PhidChkPsn\":\"\",\"ChkDt\":\"\",\"ChkFlg\":\"0\",\"LevelCode\":\"\",\"BillType\":\"5\",\"UserType\":\"\",\"RepAmtFc\":\"\",\"RepAmt\":\"\",\"RepAmtVat\":29108.21,\"RefAmtVatFc\":\"\",\"RefAmtVatEndFc\":\"\",\"ActRelAmt\":\"\",\"ChkSeq\":\"\",\"Freeze\":\"\",\"FreezeCause\":\"\",\"FreezeId\":\"\",\"PhidCntchg\":\"\",\"ImportFlg\":\"\",\"NgUpdateDt\":\"\",\"Editor\":\"\",\"CurOrgId\":\"\",\"TrFlg\":\"0\",\"TrType\":\"\",\"TrNum\":\"\",\"TrDate\":\"\",\"PointId\":\"\",\"user_mcid\":\"\",\"user_ljjjsje\":\"\",\"PhidTask\":\"\",\"AsrFlg\":\"\",\"key\":\"\"}}}";
    private static String cntpaydingridData = "{\"PhId\":\"-1\",\"PPhId\":\"\",\"Lineid\":1,\"ItemNo\":\"1181588862997534\",\"ItemName\":\"钢筋运输（平均5km内）\",\"PhidBoq\":\"0\",\"PhidBoq_EXName\":\"\",\"PhidBoqD\":\"0\",\"PhidActId\":\"0\",\"PhidActId_EXName\":\"\",\"Spec\":\"\",\"Unit\":\"758220815001001\",\"Unit_EXName\":\"kg\",\"PhidItemId\":\"0\",\"PhidItemId_EXName\":\"\",\"PhidWbs\":\"\",\"PhidWbs_EXName\":\"\",\"PhidCbs\":\"0\",\"PhidCbs_EXName\":\"\",\"PhidProjType\":\"0\",\"PhidProjType_EXName\":\"\",\"Character\":\"\",\"Demand\":\"\",\"PhidCnt\":\"758221111002017\",\"PhidCntD\":\"758221112004458\",\"PhidCfori\":\"0\",\"HzCbsWbs\":\"\",\"Prc\":0.05,\"PrcFc\":0.04587156593661898,\"PrcVat\":0.05,\"PrcVatFc\":0.05000000687091468,\"RepQty\":582164.12,\"FzQty\":0,\"CmQty\":582164.12,\"OwnQty\":582164.12,\"AppQty\":582164.12,\"Amt\":29108.21,\"AmtFc\":26704.77981651376,\"AmtVat\":29108.21,\"AmtVatFc\":29108.21,\"CmAmt\":29108.21,\"CmAmtFc\":29108.21,\"CmAmtVat\":29108.21,\"CmAmtVatFc\":29108.21,\"OwnAmt\":29108.21,\"OwnAmtFc\":29108.21,\"OwnAmtVat\":29108.21,\"OwnAmtVatFc\":29108.21,\"AppAmt\":29108.206,\"AppAmtFc\":29108.206000000002,\"AppAmtVat\":29108.21,\"AppAmtVatFc\":29108.21,\"TotalQty\":582164.12,\"TotalPct\":1,\"TaxRate\":0.09,\"Taxamt\":2403.430183486238,\"KcFreightAmt\":0,\"KcOtherAmt\":0,\"Remarks\":\"\",\"BoqType\":\"\",\"TotalAmt\":0,\"Per\":0,\"SplitFlg\":\"\",\"ItemResource\":\"pcm3_cnt_d\",\"LevelId\":\"0\",\"AddType\":\"1\",\"TimeType\":\"\",\"IsPayChange\":\"\",\"RefAmtVatFc\":0,\"RefAmtVatEndFc\":0,\"PhidFbfw\":\"0\",\"PhidFbfw_EXName\":\"\",\"NgInsertDt\":null,\"NgUpdateDt\":null,\"NgRecordVer\":0,\"Creator\":\"0\",\"Editor\":\"0\",\"CurOrgId\":\"0\",\"PhidSourceMId\":\"758221111002017\",\"PhidSourceId\":\"758221112004458\",\"ImpInfo\":\"{\\\"SSign\\\":\\\"CntD5\\\",\\\"SName\\\":\\\"合同清单信息\\\",\\\"TSign\\\":\\\"CntPayD5\\\",\\\"SchemePhId\\\":758221028000001,\\\"SOrgPhId\\\":758221028000001,\\\"SPk\\\":\\\"PhId\\\",\\\"SPkValue\\\":\\\"758221112004458\\\",\\\"STable\\\":\\\"pcm3_cnt_d\\\"}\",\"RestQty\":0,\"RestAmtVat\":0,\"RestAmtVatFc\":0,\"RestAmt\":0,\"RestAmtFc\":0,\"ControlQty\":0,\"ControlAmtVat\":0,\"ControlAmtVatFc\":0,\"ControlAmt\":0,\"ControlAmtFc\":0,\"AuxItems1\":\"\",\"AuxItems3\":\"\",\"AuxItems2\":\"\",\"PhidItemdata\":\"0\",\"PhidResBs\":\"0\",\"ResPropertys\":\"\",\"CurrType\":\"1\",\"ExchRate\":1,\"PhidPc\":\"0\",\"AuxName1\":\"\",\"AuxName2\":\"\",\"AuxName3\":\"\",\"EnterDt\":null,\"ExitDt\":null,\"UseDays\":0,\"PhidAssetType\":\"0\",\"PhidAssetType_EXName\":\"\",\"AssetProp\":\"\",\"AssetCode\":\"\",\"AssetName\":\"\",\"PhidAsset\":\"0\",\"IsFarmProduce\":0,\"iscf\":\"\",\"CompTotalQty\":0,\"Brand\":\"\",\"TotalSumBb\":0,\"TotalSumUnvatBb\":0,\"RestTotalSumBb\":0,\"RestTotalSumUnvatBb\":0,\"SumTaxrateBb\":0,\"BoqVatFc\":0,\"BoqQty\":0,\"BoqRestQty\":0,\"FyType\":\"0\",\"FySx\":\"0\",\"PhidCntType\":\"\",\"PhidNonmsunit\":\"0\",\"ResMasterData\":\"\",\"CntVatFc\":29108.21,\"CntQty\":582164.12,\"ItemDataNo\":\"\",\"BoqCode\":\"\",\"NonMsunit\":\"\",\"Area\":0,\"UmConvAm\":0,\"Weight\":\"0\",\"Vol\":\"0\",\"CBSAmt\":0,\"CBSBalance\":0,\"CBSQty\":0,\"CBSRestQty\":0,\"CBSCntSumAmt\":0,\"CBSCntTypeBalance\":0,\"IMPSourceTbl\":\"pcm3_cnt_d\",\"ThisPer\":1,\"ResOtherName\":\"\",\"ResDescript\":\"\",\"CurrType_Name\":\"人民币\",\"CompTotalAmt\":29108.21,\"CompPer\":1,\"CompThisTotalAmt\":0,\"ThisRk\":0,\"ThisBack\":0,\"ThisActRk\":0,\"RestNeedPayAmt\":0,\"ActPer\":0,\"ResourceName\":\"合同清单信息\",\"PhidPc_EXName\":\"\",\"PhidFeeType\":\"0\",\"PhidFeeType_EXName\":\"\",\"MBillType\":\"5\",\"TotalSum\":0,\"TotalSumUnVat\":0,\"SumTaxrate\":0,\"TaxrateBb\":0,\"TzAmt\":0,\"TzAmtBb\":0,\"TzAmtUntax\":0,\"TzAmtUntaxBb\":0,\"FyVatFc\":0,\"FyVat\":0,\"FyFc\":0,\"Fy\":0,\"FyTaxamt\":0,\"FyTaxamtBb\":0,\"MonPrc\":0,\"MonPrcVatFc\":0,\"MonPrcVat\":0,\"MonPrcFc\":0,\"UseMons\":0,\"MonAmtVatFc\":0,\"MonAmtVat\":0,\"MonAmtFc\":0,\"MonAmt\":0,\"MonTaxamt\":0,\"MonTaxamtBb\":0,\"JzDt\":0,\"shdjsbj\":\"\",\"FyType_EXName\":\"\",\"FySx_EXName\":\"\",\"PhidCntType_EXName\":\"\",\"user_dwgc\":\"\",\"user_fbfx\":\"\",\"user_ljjssl\":0,\"user_ljjsse\":0,\"user_ljjshsje\":0,\"user_jlgz\":\"\",\"user_fyzc\":\"\",\"user_gznr\":\"\",\"user_wzbm\":\"\",\"user_ljjsbhsje\":0,\"key\":null}";

    @Resource
    private Pcm3CntPayMMapper pcm3CntPayMMapper;
    @Resource
    private AttachmentService attachmentService;
    @Resource
    private Pcm3CntMMapper pcm3CntMMapper;
    @Resource
    private ProjectTableMapper projectTableMapper;

    /**
     * 对应i8分包合同计量结算
     *
     * @param data
     * @return
     */
    @Override
    public I8ReturnModel save(MonthlyValuations.MonthlyValuationsData.MonthlyValuationsMain data, String orgId) {
        try {
            List<Pcm3CntPayM> itemList = pcm3CntPayMMapper.selectList(Wrappers.lambdaQuery(Pcm3CntPayM.class)
                    .eq(Pcm3CntPayM::getBill_no, data.getId().toString())
                    .or()
                    .eq(Pcm3CntPayM::getUser_mcid, data.getId().toString()));
            if (itemList.size() > 0) {
                for (Pcm3CntPayM item : itemList) {
                    String user_mcid = item.getUser_mcid();
                    if (StringUtils.isEmpty(user_mcid)) {
                        item.setUser_mcid(user_mcid);
                        pcm3CntPayMMapper.updateById(item);
                    }
                }
            }

            String PhidPc = GetPhIdByCode("project_table", "user_mcxmid", orgId);//pcNo
            String PhidCnt = GetPhIdByCode("pcm3_cnt_m", "user_mcid", data.getSubcontractId().toString());
            String PhidOCode = GetCodeByCode("project_table", "cat_phid", "phid", PhidPc);//pcNo
            String RecCompName = GetCodeByCode("pcm3_cnt_m", "phid_sencomp", "phid", PhidCnt);
            //String AmtSumAll = GetCodeByCode("pcm3_cnt_m", "Cnt_Sum_Vat_Fc", "phid", PhidPc);//pcNo

            HashMap map = new HashMap<>();
            map.put("BillNo", data.getId());
            map.put("Title", data.getName());
            map.put("PhidCnt", PhidCnt);
            map.put("PhidPc", PhidPc);
            map.put("PhidOCode", PhidOCode);
            map.put("RecCompName", RecCompName);
            map.put("RecOrg", RecCompName);
            map.put("BillDt", TimeUtils.getDay(data.getCreatedAt()));
            map.put("AmtSumAll", 0.00);
            map.put("AppAmtVatFc", 0.00);
            map.put("AmtSumAllBb", 0.00);
            map.put("AppAmtVat", 0.00);
            map.put("AppAmt", 0.00);
            map.put("AppAmtFc", 0.00);
            map.put("RepAmtVat", 0.00);

            Integer Lineid = 1;
            Integer PhId = -1;
            ArrayList<HashMap<String, Object>> grid = new ArrayList<>();
            for (MonthlyValuationsItems.MonthlyValuationsItemsData.MonthlyValuationsDetail item : data.getItems()) {
                String PhidCntD = GetPhIdByCode("pcm3_cnt_d", "item_no", item.getId().toString(), " pphid = '" + PhidCnt + "'");//pcNo
                String Unit = GetPhIdByCode("msunit", "msname", item.getUnit());//pcNo

                JSONObject imp = JSONObject.parseObject("{\"SSign\":\"CntD4\",\"SName\":\"合同清单信息\",\"TSign\":\"CntPayD4\",\"SchemePhId\":169220617002006,\"SOrgPhId\":169220617001018,\"SPk\":\"PhId\",\"SPkValue\":\"169221021002436\",\"STable\":\"pcm3_cnt_d\"}");
                imp.put("SPkValue", PhidCntD);

                HashMap detail = new HashMap<>();
                detail.put("Lineid", Lineid);
                detail.put("PhId", PhId);
                detail.put("ItemNo", item.getProcedureRefId());
                detail.put("ItemName", item.getProcedureName());
                detail.put("PhidCnt", PhidCnt);
                detail.put("PhidCntD", PhidCntD);
                detail.put("PhidSourceMId", PhidCnt);
                detail.put("PhidSourceId", PhidCntD);
                detail.put("Unit", Unit);
                detail.put("ImpInfo", imp.toJSONString());
                detail.put("PrcFc", item.getPriceWithoutTax());
                detail.put("PrcVatFc", item.getPrice());
                detail.put("RepQty", item.getMeasureQuantity());
                detail.put("AmtFc", item.getAmountWithoutTax());
                detail.put("AppQty", item.getMeasureQuantity());
                detail.put("AmtVatFc", item.getAmount());
                detail.put("AppAmtVatFc", item.getAmount());
                detail.put("TaxRate", item.getTaxRate().multiply(new BigDecimal(0.01)));
                detail.put("Taxamt", item.getTaxAmount());
                grid.add(detail);
                Lineid++;
                PhId--;
            }

            String gridStr = I8Converter.SetTableRow(cntpaydingridData, grid);

            List<NameValuePair> formdata = new ArrayList<>();
            formdata.add(new BasicNameValuePair("mstformData", I8Converter.SetField(mstformData, map)));
            formdata.add(new BasicNameValuePair("cntpaydingridData", gridStr));
            formdata.add(new BasicNameValuePair("cntpaydchggridData", "{\"table\":{\"key\":\"PhId\"}}"));
            formdata.add(new BasicNameValuePair("cntpaydoutgridData", "{\"table\":{\"key\":\"PhId\"}}"));
            formdata.add(new BasicNameValuePair("cntpaydrkdgridData", "{\"table\":{\"key\":\"PhId\"}}"));
            formdata.add(new BasicNameValuePair("cntpaydingridoldData", gridStr));
            formdata.add(new BasicNameValuePair("cntpaydchggridoldData", "{\"table\":{\"key\":\"PhId\"}}"));
            formdata.add(new BasicNameValuePair("cntpaydoutgridoldData", "{\"table\":{\"key\":\"PhId\"}}"));
            formdata.add(new BasicNameValuePair("cntpaydrkdgridoldData", "{\"table\":{\"key\":\"PhId\"}}"));
            formdata.add(new BasicNameValuePair("cntpayfygridData", "{\"table\":{\"key\":\"PhId\"}}"));
            formdata.add(new BasicNameValuePair("cntpaycaldgridData", "{\"table\":{\"key\":\"PhId\"}}"));
            formdata.add(new BasicNameValuePair("cntpayrewardsgridData", "{\"table\":{\"key\":\"PhId\"}}"));
            formdata.add(new BasicNameValuePair("cntpaysplitgridData", "{\"table\":{\"key\":\"PhId\"}}"));
            formdata.add(new BasicNameValuePair("cntmodel", "4"));
            formdata.add(new BasicNameValuePair("bustype", "PAY4"));
            formdata.add(new BasicNameValuePair("imptaskid", ""));
            formdata.add(new BasicNameValuePair("attachOutGuid", ""));
            formdata.add(new BasicNameValuePair("isContinue", "false"));
            formdata.add(new BasicNameValuePair("attchmentGuid", "0"));
            formdata.add(new BasicNameValuePair("ng3_logid", "0"));

            I8ReturnModel<String> res = i8Request.PostFormSyncByOcode("/PMS/PCM/CntPayM/save", formdata, "101");
            if(res.getIsOk()){
                return I8ReturnModel.success();
            }
            throw new RuntimeException(res.getMessage());
        } catch (Exception ex) {
            ngLog.error("MonthlyValuationsImpl", "月度计划保存异常", ex.getMessage());
            return I8ReturnModel.error(ex.getMessage());
        }
    }


    /**
     * 对应i8分包合同计量结算
     *
     * @param data
     * @return
     */
    @Override
    public I8ReturnModel saveLW(MonthlyValuations.MonthlyValuationsData.MonthlyValuationsMain data, String projectId) {
        try {
            ngLog.info("MonthlyValuationsImpl", "月度计划报文:" + JSONObject.toJSONString(data), projectId, "pcm3_cnt_pay_m");
            List<Pcm3CntPayM> itemList = pcm3CntPayMMapper.selectList(Wrappers.lambdaQuery(Pcm3CntPayM.class)
                    .eq(Pcm3CntPayM::getBill_no, data.getId().toString())
                    .or()
                    .eq(Pcm3CntPayM::getUser_mcid, data.getId().toString()));
            if (itemList.size() > 0) {
                for (Pcm3CntPayM item : itemList) {
                    String user_mcid = item.getUser_mcid();
                    if (StringUtils.isEmpty(user_mcid)) {
                        item.setUser_mcid(user_mcid);
                        pcm3CntPayMMapper.updateById(item);
                    }
                }
                return I8ReturnModel.success("已同步，无需反复同步");
            }

            String PhidPc = GetPhIdByCode("project_table", "user_mcxmid", projectId);//pcNo
            String PhidCnt = GetPhIdByCode("pcm3_cnt_m", "user_mcid", data.getSubcontractId().toString());
            String PhidOCode = GetCodeByCode("project_table", "cat_phid", "phid", PhidPc);//pcNo
            String RecCompName = GetCodeByCode("pcm3_cnt_m", "phid_sencomp", "phid", PhidCnt);
            //String AmtSumAll = GetCodeByCode("pcm3_cnt_m", "Cnt_Sum_Vat_Fc", "phid", PhidPc);//pcNo
            Double AmtSumAll = data.getItems().stream().mapToDouble(t -> t.getAmount().doubleValue()).sum();
            HashMap map = new HashMap<>();
            map.put("BillNo", data.getId());
            map.put("Title", data.getName());
            map.put("PhidCnt", PhidCnt);
            map.put("PhidPc", PhidPc);
            map.put("PhidOCode", "758220810001001");
            map.put("RecCompName", RecCompName);
            map.put("RecOrg", PhidOCode);
            map.put("BillDt", TimeUtils.getDay(data.getCreatedAt()));
            map.put("AmtSumAll", AmtSumAll);
            map.put("AppAmtVatFc", data.getAmount());
            map.put("AmtSumAllBb", 0);
            map.put("AppAmtVat", 0);
            map.put("AppAmt", 0);
            map.put("AppAmtFc", 0);
            map.put("RepAmtVat", 0);
            map.put("PhidSchemeId", "758221028000001");
            map.put("user_mcid", data.getId());
            map.put("BillType", "5");
            map.put("PhidCntType", "758220811000002");
            map.put("DtStart", data.getValuationBeginDate());
            map.put("DtEnd", data.getValuationEndDate());
            map.put("user_jjqs", data.getValuationNo());
            map.put("user_bqbhsje", data.getAmountWithoutTax());
            map.put("user_ljjsbshje", data.getCumulativeAmountWithoutTax());
            map.put("SumPayAmt", data.getCumulativeAmount());
            map.put("user_bqse", data.getTaxAmount());
            map.put("user_ljjsse", data.getCumulativeTaxAmount());
            map.put("user_ljjjsje", data.getCumulativeAmount().doubleValue());

            Integer Lineid = 1;
            Integer PhId = -1;
            ArrayList<HashMap<String, Object>> grid = new ArrayList<>();
            for (MonthlyValuationsItems.MonthlyValuationsItemsData.MonthlyValuationsDetail item : data.getItems()) {
                String PhidCntD = GetPhIdByCode("pcm3_cnt_d", "user_mcid", item.getProcedureRefId().toString(), " pphid = '" + PhidCnt + "'");//pcNo
                String Unit = GetPhIdByCode("msunit", "msname", item.getUnit());//pcNo
                HashMap detail = new HashMap<>();
                if (StringUtils.isEmpty(PhidCntD)) {
                    detail.put("ImpInfo", "");
                    detail.put("PhidCntD", "");
                    detail.put("PhidSourceId", "");
                } else {
                    JSONObject imp = JSONObject.parseObject("{\"SSign\":\"CntD4\",\"SName\":\"合同清单信息\",\"TSign\":\"CntPayD4\",\"SchemePhId\":169220617002006,\"SOrgPhId\":169220617001018,\"SPk\":\"PhId\",\"SPkValue\":\"169221021002436\",\"STable\":\"pcm3_cnt_d\"}");
                    imp.put("SPkValue", PhidCntD);
                    detail.put("ImpInfo", imp.toJSONString());
                    detail.put("PhidCntD", PhidCntD);
                    detail.put("PhidSourceId", PhidCntD);
                }
                detail.put("PhId", PhId);
                detail.put("Lineid", Lineid);
                detail.put("ItemNo", item.getId());
                detail.put("ItemName", item.getProcedureName());
                detail.put("PhidCnt", PhidCnt);
                detail.put("PhidSourceMId", PhidCnt);
                detail.put("Unit", Unit);
                detail.put("PrcFc", item.getPriceWithoutTax());
                detail.put("PrcVatFc", item.getPrice());
                detail.put("RepQty", item.getValuationQuantity());
                detail.put("AmtFc", item.getAmountWithoutTax());
                detail.put("AppQty", item.getMeasureQuantity());
                detail.put("AmtVatFc", item.getAmount());
                detail.put("AppAmtVatFc", item.getAmount());
                detail.put("TaxRate", item.getTaxRate().multiply(new BigDecimal(0.01)));
                detail.put("Taxamt", item.getTaxAmount());
                detail.put("user_mcid", item.getId());
                detail.put("user_dwgc", item.getProjectUnitWorkName());
                detail.put("user_fbfx", item.getEntryWorkName());
                detail.put("user_wzbm", item.getFullCode());
                detail.put("user_ljjssl", item.getCumulativeValuationQuantity());
                detail.put("user_ljjsbhsje", item.getCumulativeAmountWithoutTax());
                detail.put("user_ljjsse", item.getCumulativeTaxAmount());
                detail.put("user_ljjshsje", item.getCumulativeAmount());
                detail.put("MBillType", "5");
                grid.add(detail);
                Lineid++;
                PhId--;
            }
            String main = I8Converter.SetField(mstformData, map);
            String gridStr = I8Converter.SetTableRow(cntpaydingridData, grid);
            List<NameValuePair> formdata = new ArrayList<>();
            formdata.add(new BasicNameValuePair("mstformData", main));
            formdata.add(new BasicNameValuePair("cntpaydingridData", gridStr));
            formdata.add(new BasicNameValuePair("cntpaydchggridData", "{\"table\":{\"key\":\"PhId\"}}"));
            formdata.add(new BasicNameValuePair("cntpaydoutgridData", "{\"table\":{\"key\":\"PhId\"}}"));
            formdata.add(new BasicNameValuePair("cntpaydrkdgridData", "{\"table\":{\"key\":\"PhId\"}}"));
            formdata.add(new BasicNameValuePair("cntpaydingridoldData", gridStr));
            formdata.add(new BasicNameValuePair("cntpaydchggridoldData", "{\"table\":{\"key\":\"PhId\"}}"));
            formdata.add(new BasicNameValuePair("cntpaydoutgridoldData", "{\"table\":{\"key\":\"PhId\"}}"));
            formdata.add(new BasicNameValuePair("cntpaydrkdgridoldData", "{\"table\":{\"key\":\"PhId\"}}"));
            formdata.add(new BasicNameValuePair("cntpaydescgridData", "{\"table\":{\"key\":\"PhId\"}}"));
            formdata.add(new BasicNameValuePair("cntpayfygridData", "{\"table\":{\"key\":\"PhId\"}}"));
            formdata.add(new BasicNameValuePair("cntpaycaldgridData", "{\"table\":{\"key\":\"PhId\"}}"));
            formdata.add(new BasicNameValuePair("cntpayrewardsgridData", "{\"table\":{\"key\":\"PhId\"}}"));
            formdata.add(new BasicNameValuePair("cntpaysplitgridData", "{\"table\":{\"key\":\"PhId\"}}"));
            formdata.add(new BasicNameValuePair("cntmodel", "5"));
            formdata.add(new BasicNameValuePair("bustype", "PAY5"));
            formdata.add(new BasicNameValuePair("imptaskid", ""));
            formdata.add(new BasicNameValuePair("attachOutGuid", ""));
            formdata.add(new BasicNameValuePair("isContinue", "false"));
            formdata.add(new BasicNameValuePair("attchmentGuid", "0"));
            formdata.add(new BasicNameValuePair("ng3_logid", "0"));
            I8ReturnModel<String> res = i8Request.PostFormSyncByOcode("/PMS/PCM/CntPayM/save", formdata, "101");
            ngLog.info("MonthlyValuationsImpl", "月度计划保存结果" + res, data.getId().toString(), "pcm3_cnt_pay_m");
            if (res.getIsOk()) {
                String phid = res.getPhId();
                List<AttachMentMonthly> attachMentList = data.getAttachMentsList();
                for (AttachMentMonthly item : attachMentList) {
                    String name = item.getAttachmentName();
                    String url = item.getResourceUrl();
                    String dataBytes = attachmentService.downloadFile(url);
                    attachmentService.postFile(phid, "pcm3_cnt_pay_m", name, dataBytes, "asr_info");
                }
                return I8ReturnModel.success();
            }
            return I8ReturnModel.error(res.getMessage());
        } catch (Exception ex) {
            ngLog.error("MonthlyValuationsImpl", "月度计划保存异常", ex.getMessage(), projectId, "pcm3_cnt_pay_m");
            return I8ReturnModel.error(ex.getMessage());
        }
    }

    @Override
    public void saveBatch(List<MonthlyValuations.MonthlyValuationsData.MonthlyValuationsMain> data, String projectId) {
        for (MonthlyValuations.MonthlyValuationsData.MonthlyValuationsMain item : data) {
            saveLW(item, projectId);
        }
    }

    @Override
    public List<MonthlyValuations.MonthlyValuationsData.MonthlyValuationsMain> getData(String projectId, String subcontractId) {
        List<MonthlyValuations.MonthlyValuationsData.MonthlyValuationsMain> dataList = new ArrayList<>();
        while (true) {
            try {
                String apiUrl = String.format(mainApi, projectId, subcontractId);
                RequestResult dataBody = client.get(apiUrl);
                String content = dataBody.getContent();
                if (StringUtils.isEmpty(content)) {
                    break;
                }
                MonthlyValuations res = JSONObject.parseObject(content, MonthlyValuations.class);
                List<MonthlyValuations.MonthlyValuationsData.MonthlyValuationsMain> dataArray = res.getData().getMonthlyValuations();
                dataList.addAll(dataArray);
                break;
            } catch (Exception ex) {
                logger.info(String.format("call api error:  %s", ex.getMessage()), ex);
                break;
            }
        }
        return dataList.stream().distinct().collect(Collectors.toList());
    }

    /**
     * @param projectId     项目id
     * @param subcontractId 合同id
     * @param valuationId   计价id
     * @return
     */
    public List<MonthlyValuationsItems.MonthlyValuationsItemsData.MonthlyValuationsDetail> getDData(String projectId, String subcontractId, String valuationId) {
        List<MonthlyValuationsItems.MonthlyValuationsItemsData.MonthlyValuationsDetail> dataList = new ArrayList<>();
        while (true) {
            try {
                String apiUrl = String.format(detailApi, projectId, subcontractId, valuationId);
                RequestResult dataBody = client.get(apiUrl);
                String content = dataBody.getContent();
                if (StringUtils.isEmpty(content)) {
                    break;
                }
                MonthlyValuationsItems res = JSONObject.parseObject(content, MonthlyValuationsItems.class);
                List<MonthlyValuationsItems.MonthlyValuationsItemsData.MonthlyValuationsDetail> dataArray = res.getData().getItems();
                dataList.addAll(dataArray);
                break;
            } catch (Exception ex) {
                logger.info(String.format("call api error:  %s", ex.getMessage()), ex);
                break;
            }
        }
        return dataList.stream().distinct().collect(Collectors.toList());
    }

    private List<AttachMentMonthly> getAttachementData(String projectId, Long valuationId) {
        List<AttachMentMonthly> dataList = new ArrayList<>();
        while (true) {
            try {
                String apiUrl = String.format(attachApi, projectId, valuationId);
                RequestResult dataBody = client.get(apiUrl);
                String content = dataBody.getContent();
                if (StringUtils.isEmpty(content)) {
                    break;
                }
                List<AttachMentMonthly> res = com.alibaba.fastjson.JSONObject.parseArray(content, AttachMentMonthly.class);
                return res;
            } catch (Exception ex) {
                logger.info(String.format("获取表头信息:  %s", ex.getMessage()), ex);
                break;
            }
        }
        return dataList;
    }

    @Override
    public I8ReturnModel getDataByOrgId(String projectId, String subcontractId) {
        return I8ReturnModel.success("获取数据成功", getDataListByOrgId(projectId, subcontractId));
    }

    @Async("asyncServiceExecutor")
    @Override
    public I8ReturnModel saveDataByOrgId(String projectId, String subcontractId) {
        try {
            List<MonthlyValuations.MonthlyValuationsData.MonthlyValuationsMain> data = getDataListByOrgId(projectId, subcontractId);
            if (data.size() == 0) {
                return I8ReturnModel.success(projectId + "-项目，未获取的需要同步的数据");
            }
            saveBatch(data, projectId);
        } catch (Exception ex) {
            return I8ReturnModel.error(ex.getMessage());
        }
        return I8ReturnModel.success();
    }

    @Override
    public I8ReturnModel saveDataByOrgIdAll(String projectId) {
        try {
            ProjectTable projectTable = projectTableMapper.selectOne(Wrappers.lambdaQuery(ProjectTable.class)
                    .eq(ProjectTable::getUser_mcxmid, projectId));
            if (projectTable == null) {
                throw new RuntimeException("项目信息id" + projectId + "，不存在");
            }
            List<Pcm3CntM> pcm3CntMList = pcm3CntMMapper.selectList(Wrappers.lambdaQuery(Pcm3CntM.class)
                    .isNotNull(Pcm3CntM::getUser_mcid)
                    .eq(Pcm3CntM::getPhid_pc, projectTable.getPhid()));
            for (Pcm3CntM item : pcm3CntMList) {
                List<MonthlyValuations.MonthlyValuationsData.MonthlyValuationsMain> data = getDataListByOrgId(projectId, item.getUser_mcid());
                if (data.size() > 0) {
                    saveBatch(data, projectId);
                } else {
                    return I8ReturnModel.success(projectId + "-项目，未获取的需要同步的数据");
                }
            }
        } catch (Exception ex) {
            return I8ReturnModel.error(ex.getMessage());
        }
        return I8ReturnModel.success();
    }

    public List<MonthlyValuations.MonthlyValuationsData.MonthlyValuationsMain> getDataListByOrgId(String projectId, String subcontractId) {
        List<MonthlyValuations.MonthlyValuationsData.MonthlyValuationsMain> main = getData(projectId, subcontractId);
        for (MonthlyValuations.MonthlyValuationsData.MonthlyValuationsMain item : main) {
            List<MonthlyValuationsItems.MonthlyValuationsItemsData.MonthlyValuationsDetail> detail = getDData(projectId, subcontractId, item.getId().toString());
            if (detail.size() > 0) {
                item.setItems(detail);
            } else {
                item.setItems(new ArrayList<>());
            }
            List<AttachMentMonthly> attachMentList = getAttachementData(projectId, item.getId());
            if (attachMentList.size() > 0) {
                item.setAttachMentsList(attachMentList);
            }
        }
        return main;
    }
}
